package com.zywl.api;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.gson.Gson;
import com.zywl.utils.models.JsonResult;
import com.zywl.utils.utils.Constants;
import com.zywl.utils.utils.FileUtil;
import com.zywl.web.controller.base.BaseController;
import com.zywl.xfyun.sign.LfasrSignature;
import com.zywl.xfyun.utils.HttpUtil;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.zip.Inflater;

@RestController
@RequestMapping("/api/audiotransfer/")
public class AudioTransferApi extends BaseController {
    private static final Gson gson = new Gson();

    @ResponseBody
    @RequestMapping("transfer")
    public JsonResult transfer(HttpServletRequest request,String path){
        JsonResult jr = new JsonResult();
        try {
            String filePath = FileUtil.getFileRealPathForServer(request, path);
            String result = upload(filePath);
            String jsonStr = StringEscapeUtils.unescapeJavaScript(result);
            String orderId = String.valueOf(JSONUtil.getByPath(JSONUtil.parse(jsonStr), "content.orderId"));
            String content = getResult(orderId);
            jr.success("语音转写成功",content);
        }catch (Exception e){
            logger.error("语音转写错误",e);
            jr.error("语音转写错误");
        }
        return jr;
    }

    public String upload(String path) throws Exception {
        HashMap<String, Object> map = new HashMap<>(16);
        File audio = new File(path);
        String fileName = audio.getName();
        long fileSize = audio.length();
        map.put("appId", Constants.XF_APPID);//
        map.put("fileSize", fileSize);
        map.put("fileName", fileName);
        map.put("duration", "200");
        LfasrSignature lfasrSignature = new LfasrSignature(Constants.XF_APPID, Constants.XF_KEYSECRET);
        map.put("signa", lfasrSignature.getSigna());
        map.put("ts", lfasrSignature.getTs());
        String paramString = HttpUtil.parseMapToPathParam(map);
        String url = Constants.XF_HOST + "/v2/api/upload" + "?" + paramString;
        String response = HttpUtil.iflyrecUpload(url, new FileInputStream(audio));
        return response;
    }

    public String getResult(String orderId) throws Exception {
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("orderId", orderId);
        LfasrSignature lfasrSignature = new LfasrSignature(Constants.XF_APPID, Constants.XF_KEYSECRET);
        map.put("signa", lfasrSignature.getSigna());
        map.put("ts", lfasrSignature.getTs());
        map.put("appId", Constants.XF_APPID);
        map.put("resultType", "transfer,predict");
        String paramString = HttpUtil.parseMapToPathParam(map);
        String url = Constants.XF_HOST + "/v2/api/getResult" + "?" + paramString;
        while (true) {
            String response = HttpUtil.iflyrecGet(url);
            JsonParse jsonParse = gson.fromJson(response, JsonParse.class);
            if (jsonParse.content.orderInfo.status == 4 || jsonParse.content.orderInfo.status == -1) {
                String content = jiexi(response);
                return content;
            } else {
                logger.info("进行中...，状态为:" + jsonParse.content.orderInfo.status);
                //建议使用回调的方式查询结果，查询接口有请求频率限制
                Thread.sleep(5000);
            }
        }
    }

    /**
     * 解析接口返回的结果，提取文字
     * @param response
     * @return
     */
    public String jiexi(String response){
        StringBuilder sb = new StringBuilder();
        JSONObject jsonObject = new JSONObject(response);
        Object content = jsonObject.get("content");
        JSONObject contentjsonObject = new JSONObject(content);
        Object orderResult = contentjsonObject.get("orderResult");
        JSONObject orderResultjsonObject = new JSONObject(orderResult);
        Object lattice = orderResultjsonObject.get("lattice");
        JSONArray jsonArray= new JSONArray(lattice);
        for (int i=0;i<jsonArray.size();i++){
            JSONObject latticeJb = new JSONObject(jsonArray.get(i));
            Object json_1best = latticeJb.get("json_1best");
            JSONObject json_1bestjsonObject = new JSONObject(json_1best);
            Object st = json_1bestjsonObject.get("st");
            JSONObject stjsonObject = new JSONObject(st);
            Object rt = stjsonObject.get("rt");
            JSONArray rtjsonArray= new JSONArray(rt);
            for (int j=0;j<rtjsonArray.size();j++){
                JSONObject rtjsonObject = new JSONObject(rtjsonArray.get(j));
                Object ws = rtjsonObject.get("ws");
                JSONArray wsjsonArray= new JSONArray(ws);
                for (int k=0;k<wsjsonArray.size();k++){
                    JSONObject wsjsonObject = new JSONObject(wsjsonArray.get(k));
                    Object cw = wsjsonObject.get("cw");
                    JSONArray cwjsonArray= new JSONArray(cw);
                    for (int l = 0;l < cwjsonArray.size();l++){
                        JSONObject cwjsonObject = new JSONObject(cwjsonArray.get(l));
                        Object w = cwjsonObject.get("w");
                        sb.append(w);
                    }
                }
            }
        }
        return sb.toString();
    }


    public void write(String resp) throws Exception {
        //将写入转化为流的形式
        BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\test.txt"));
        String ss = resp;
        bw.write(ss);
        //关闭流
        bw.close();
        System.out.println("写入txt成功");
    }

    class JsonParse {
        Content content;
    }

    class Content {
        OrderInfo orderInfo;
    }

    class OrderInfo {
        Integer status;
    }

}
